import math
import os
import shutil
import time

import numpy as np
from scipy.optimize import curve_fit
from tools.tools import create_clear_dir

np.seterr(over='ignore')
import matplotlib.pyplot as plt

resolutions = [240, 360, 480, 640, 720, 960, 1080, 1280]


def adjust_resolution(threshold, acc_list, resolution_list):
    assert len(acc_list) != len(resolution_list)
    for i in range(len(acc_list)):
        if acc_list[i] >= threshold:
            return resolution_list[i], i


# acc_list = [0.1, 0.3, 0.5, 0.7, 0.87 , 0.88]
# resolution_list = [240, 360, 480, 640, 720, 960, 1080, 1280]
# print(adjust_resolution(0.8, acc_list, resolution_list))

def psi(x, a, b, c):
    return b / (np.exp(-a * x) + 1) + c


def my_psi(f):
    return 1 / (np.exp(-8 * f) + 1) + 2


x_data = np.linspace(0, 1, 10)
y_data = [my_psi(f) for f in x_data]

[a, b, c], _ = curve_fit(psi, x_data, y_data)
y_pred = [psi(f, a, b, c) for f in x_data]


# plt.figure()
# plt.plot(x_data, y_data,'--')
# plt.plot(x_data, y_pred,'*')
# plt.legend(["Sigmod","Psi"])
# plt.show()

def adjust_sample():
    pass


def sample_result(resolution=1280, sample_rate=0.8):
    start = time.time()
    root_path = r"E:\GraduationProject\datasets\AuAir\scene8"
    images_path = root_path + r"\images"
    images_label = os.path.join(root_path, 'predict' + str(resolution))
    predict_sample = os.path.join(root_path, "predict" + str(resolution) + "_sample_" + str(sample_rate))
    create_clear_dir(predict_sample)
    images_names = os.listdir(images_path)
    images_numbers = len(images_names)

    video_flag = np.full(images_numbers, False, dtype=bool)  # 记录对应下标位置的图象是否需要预测
    sample_length = int(sample_rate * images_numbers)  # 计算需要采样的个数
    save_index = np.round(np.linspace(0, images_numbers - 1, sample_length)).astype(int)  # 计算需要保存的图片的索引

    video_flag[0] = True  # 第一张一定要检测
    for index in save_index:
        video_flag[index] = True

    for index, image in enumerate(images_names):
        label = images_names[index].replace("jpg", "txt")
        dst = os.path.join(predict_sample, label)
        if video_flag[index]:
            src = os.path.join(images_label, label)
        else:
            pointer = index - 1
            while video_flag[pointer] is False:  # 向前寻找最近的一个检测框
                pointer -= 1
            label = images_names[pointer].replace("jpg", "txt")
            src = os.path.join(images_label, label)
        shutil.copy(src, dst)

    end = time.time()
    print('采样率为：{}时的执行总时间为{}'.format(sample_rate, end - start))


for r in resolutions:
    for sample in range(1, 10):
        sample_result(r, sample / 10)
